<template>
  <div class="page-container">
    <el-form
      class="el-form-modify"
      ref="form"
      label-width="100px"
      :model="formData"
      :rules="rules"
      style="padding-top: 40px"
    >
      <el-form-item label="原始密码" prop="oldPwd">
        <el-input v-model="formData.oldPwd" type="password" placeholder="请输入原始密码" autocomplete="off" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input v-model="formData.newPwd" type="password" placeholder="请输入原始密码" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="确认新密码" prop="newPwd1">
        <el-input v-model="formData.newPwd1" type="password" placeholder="请输入原始密码" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save" size="small" :loading="saving"
          >保存</el-button
        >
        <el-button @click="cancel" size="small">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { editPassword } from "@/api/user";
export default {
  name: "ResetPassword",
  data() {
    return {
      formData: {
        oldPwd: "",
        newPwd: "",
        newPwd1: ""
      },
      rules: {
        oldPwd: [
          { required: true, trigger: "change", message: '必填项' }
        ],
        newPwd: [
          { required: true, trigger: "change", validator: this.validatePwd},
        ],
        newPwd1: [
          { required: true, trigger: "change", message: '必填项'}, 
          { trigger: "change", validator: this.validatePwdRepeat},
        ],
      },
      saving: false
    };
  },
  methods: {
    validatePwd(rule, value, callback) {
      if (value == '') {
        return callback(new Error('必填项'))
      }
      if (value !== '') {
        this.$refs.form.validateField('newPwd1')
      }
      callback()
    },
    validatePwdRepeat(rule, value, callback) {
      if (value != this.formData.newPwd) {
        return callback(new Error('两次密码必须一样'))
      }
      callback()
    },
    save() {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return;
        }
        try {
          this.saving = true;
          await editPassword(this.formData);
          this.saving = false;
          this.$message.success('修改密码成功，请重新登录')
          await this.$store.dispatch('user/logout')
          this.$router.push(`/login?redirect=/dashboard`)
        } catch (err) {
          this.saving = false;
        }
      });
    },
    cancel() {
      this.$router.go(-1);
    }
  }
};
</script>

<style lang="scss">
.pagination-title {
  font-weight: normal;
}
.OrderDetails {
  display: flex;
  justify-content: space-between;
}
</style>
